package cn.com.dhcc.app.pub.module.usermgr.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.annotation.CoreMenuCode;
import cn.com.dhcc.app.core.annotation.CoreMenuCode.CORE_LEAF_MENU;
import cn.com.dhcc.app.core.annotation.WsdNoNeedAuth;
import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.base.log.LogType;
import cn.com.dhcc.app.core.base.user.AuthUserType;
import cn.com.dhcc.app.core.component.db.orm.WhereCondition;
import cn.com.dhcc.app.core.component.log.Log;
import cn.com.dhcc.app.core.component.pager.Pager;
import cn.com.dhcc.app.core.component.pager.PagerData;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.tag.CommonStaticCode.ENTITY_STATUS;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.tag.CommonStaticCode.YESNO;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.AppPara.UAMS;
import cn.com.dhcc.app.pub.module.authmgr.service.AuthService;
import cn.com.dhcc.app.pub.module.authmgr.vo.RoleInfoInner;
import cn.com.dhcc.app.pub.module.login.service.LoginService;
import cn.com.dhcc.app.pub.module.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.pub.module.usermgr.service.RelUserRoleInfoService;
import cn.com.dhcc.app.pub.module.usermgr.vo.RelUserRole;
import cn.com.dhcc.app.pub.module.usermgr.vo.UserInfoVo;
/**
 * 用户管理
 * @author joe
 * @time  2016-4-14 下午4:48:23
 */
@Controller
@RequestMapping("pub/sysmgr/usermgr/")
@CoreMenuCode(belongToMenu=CORE_LEAF_MENU.USER_MGR)
public class CmUserMgrController extends BaseController{

	@Autowired
	private CmUserMgrService userMgrService;
	@Autowired
	private LoginService loginService;
	@Autowired
	private AuthService authService;
	@Autowired
	RelUserRoleInfoService relUserRoleInfoService;
	
	Logger logger = Log.getLogger(LogType.BUSILOG);
	
	@RequestMapping("user_list")
	public String userList(Model model,Pager pager,UserInfoVo userInfoVo,String order,String orderName){
		try{
			PagerData<UserInfoVo> pagerData = userMgrService.listUser(pager,userInfoVo, order, orderName);
			model.addAttribute("users", pagerData.getDatas());
			setTotoal(model, pagerData.getTotal());
		} catch (ServiceException e) {
			return toAlertPage(model, "获取用户列表失败");
		}
		return "pub/sysmgr/usermgr/user_list";
	}
	
	@RequestMapping(value="user_add")
	public String userAdd(Model model){
		return "pub/sysmgr/usermgr/user_add";
	}
	
	@RequestMapping(value="add_user",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addUser(Model model,UserInfoVo user){
		try{
			if(user!=null){
				 user.setId(UUIDGenerator.getUUID());
				 user.setAdmin(YESNO.NO.getStatus());
				 user.setModified(new Date());
				 user.setStatus(ENTITY_STATUS.ENABLE.getCode());
				 userMgrService.addUser(user);
			}else{
				return jsonFailResult("操作失败,缺少参数");
			}
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		}catch (Exception e) {
			logger.error(e);
			return jsonFailResult("操作失败");
		}
		return jsonSuccessResult("添加成功");
	}
	
	@RequestMapping(value = "user_update")
	public String update(String id, Model model) {
		try {
			model.addAttribute(VO_KEY, userMgrService.getUserById(id));
		} catch (ServiceException e) {
			return toAlertPage(model, e.getMessage());
		}
		return "pub/sysmgr/usermgr/user_update";
	}
	
	@RequestMapping(value="update_user")
	@ResponseBody
	public Map<String, Object> updateUser(Model model,UserInfoVo user,HttpSession session){
		try{
			user.setModified(new Date());
			user.setAdmin(YESNO.NO.getStatus());
			userMgrService.updateUser(user);
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		} catch (ServiceException e) {
			return jsonFailResult("修改失败");
		}
		return jsonSuccessResult("修改成功");
	}
	
	@RequestMapping(value="get_user")
	public String getUser(Model model,String id){
		try{
			if(!StringUtils.hasText(id))return toAlertPage(model, "缺少参数");
			UserInfoVo userInfo = userMgrService.getUserById(id);
			if(userInfo==null){
				return toAlertPage(model, "用户不存在");
			}else{
				model.addAttribute("vo", userInfo);
			}
		}catch (ServiceException e) {
			return toAlertPage(model, "操作失败");
		} 
		return "pub/sysmgr/usermgr/user_info";
	}
	
	@RequestMapping("del_user")
	@ResponseBody
	public Map<String, Object>  delUser(Model model, String id){
		try{
			if(!StringUtils.hasText(id))return jsonFailResult("操作失败，用户id不能为空！");
			userMgrService.deleteUserById(id);
			return jsonSuccessResult("删除用户成功");
		} catch (Exception e) {
			return jsonFailResult("删除用户失败");
		}
	}
	
	@RequestMapping("disable_user")
	@ResponseBody
	public Map<String, Object>  disableRole(String id){
		try{
			userMgrService.changeUserStatus(id,ENTITY_STATUS.DISABLE);
			 return jsonSuccessResult("暂停用户成功");
		} catch (ServiceException e) {
			return jsonFailResult("暂停用户失败");
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		}
	}
	@RequestMapping("enable_user")
	@ResponseBody
	public Map<String, Object>  enableRole( String id){
		try{
			userMgrService.changeUserStatus(id,ENTITY_STATUS.ENABLE);
			 return jsonSuccessResult("开启用户成功");
		} catch (NiceException e) {
			return jsonFailResult(e.getMessage());
		}catch (Exception e) {
			return jsonFailResult("开启用户失败");
		}
	}
	
	@RequestMapping("isNameAvailable")
	@ResponseBody
	public String nameCheck(Model model, String userName,String oldValue){
		
		try {
			if (userMgrService.isPropertyUnique("username", userName, oldValue)) {
				return FORM_CHECK_SUCCESS;
			} else {
				return FORM_CHECK_FAIL;
			}
		} catch (ServiceException e) {
			return FORM_CHECK_FAIL;
		}
	}
	
	@RequestMapping(value = "/user_role_choose_role")
	public String userChooseRole(Model model,String userId) {
		String msg = "";
		try {
			if(!StringUtils.hasText(userId))return toAlertPage(model, "缺少参数");
			UserInfoVo userInfo = userMgrService.getUserById(userId);
			if(userInfo==null){
				return toAlertPage(model, "用户不存在");
			}else{
				model.addAttribute(VO_KEY, userInfo);
			}
			
			List<RoleInfoInner> roleInfoList = relUserRoleInfoService.getRoleListByUser(userId);
			model.addAttribute("roleInfoList", roleInfoList);
			
			return "pub/sysmgr/usermgr/user_role_choose_role";
		} catch (ServiceException e) {
			msg = "根据用户编码获取用户下角色信息失败";
			return toAlertPage(model, e.getMessage());
		} catch (Exception e) {
			msg = "根据用户编码获取用户下角色出现异常";
			logger.error(msg, e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	@RequestMapping("/user_role_role_add")
	public String userRoleAdd(Model model, String id, HttpSession httpSession) {
		String msg = "";
		try {
			UserInfoVo userInfo = userMgrService.getUserById(id);
			model.addAttribute(VO_KEY, userInfo);
			
			List<RoleInfoInner> otherRoleInfoList = new ArrayList<RoleInfoInner>();
			
			List<RoleInfoInner> roleInfoList = relUserRoleInfoService.getRoleListByUser(id);
			int roleType = 0;
			for (RoleInfoInner roleInfo : roleInfoList) {
				roleType = roleType|Integer.parseInt(roleInfo.getRoleType());
			}
			
			otherRoleInfoList = relUserRoleInfoService.getOtherRoleList(id.trim(), String.valueOf(roleType));
			model.addAttribute("otherRoleInfoList", otherRoleInfoList);
			
			return "pub/sysmgr/usermgr/user_role_role_add";
		} catch (ServiceException e) {
			msg = "添加用户下角色出现异常";
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			logger.error(msg, e);
			return toAlertPage(model, e.getMessage());
		} catch (Exception e) {
			msg = "添加用户下角色出现异常";
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			logger.error(msg, e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	/**
	 * 判断是否同时包含某个类型的角色
	 * @param roles
	 * @return
	 */
	private boolean contains(List<RoleInfoInner> roles,AuthUserType type){
		if (roles==null || roles.isEmpty()) {
			return false;//验证通过
		}
		for (int i = 0; i < roles.size(); i++) {
			RoleInfoInner r=roles.get(i);//
			if (type.getCode().equals(r.getRoleType())) {//包含某个角色类型
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 增加用户角色信息，更新数据库
	 */
	@RequestMapping(value = "/add_user_role_role")
	@ResponseBody
	public Map<String, Object> addUserRole(Model model, String userId,String roleIds, HttpSession httpSession) {
		String msg = "";
		try {
			List<RelUserRole> relUserRoleList = new ArrayList<RelUserRole>();
			List<RoleInfoInner> curRoleList = relUserRoleInfoService.getRoleListByUser(userId);
			String[] roleArray = roleIds.split(",");
			WhereCondition parameter = new WhereCondition();
			parameter.where().eq("1", "1");
			if(roleArray == null || roleArray.length == 0){
				parameter.and().eq("1", "2");
			}else{
				parameter.and().in("id", roleArray);
			}
			List<RoleInfoInner> roleInfoList = authService.listRole(parameter);
			//同时包含安全保密管理员、安全审计员
			if(contains(roleInfoList, AuthUserType.SAFETY_OFFICER) && contains(roleInfoList, AuthUserType.AUDIT_OFFICER)){
				throw new NiceException("选择的用户角色中同时包含安全保密管理员、安全审计员");
			}
			//验证数据库里与提交的合起来是否同时 安全保密管理员、安全审计员--有必要进一步验证
			if (contains(roleInfoList, AuthUserType.SAFETY_OFFICER) || contains(roleInfoList, AuthUserType.AUDIT_OFFICER)) {
				//
				List<RoleInfoInner> all=new ArrayList<RoleInfoInner>(curRoleList);
				all.addAll(roleInfoList);
				if(contains(all, AuthUserType.SAFETY_OFFICER) && contains(all, AuthUserType.AUDIT_OFFICER)){
					throw new NiceException("选择的用户角色和数据库中已存在的角色同时包含安全保密管理员、安全审计员");
				}
			}
			
			for (int i = 0; i < roleArray.length; i++) {
				String roleId = roleArray[i];
				if(!curRoleList.contains(roleId)){
					RelUserRole vo = new RelUserRole();
					vo.setRoleId(roleId);
					vo.setUserId(userId);
					WhereCondition whereCondition = new WhereCondition();
					whereCondition.where().eq("role_id", roleId).and().eq("user_id", userId);
					if(relUserRoleInfoService.countUserRole(whereCondition)>0){
						relUserRoleInfoService.insertOrUpdateUserRole(vo);
					}else{
						relUserRoleList.add(vo);
					}
				}
			}
			if(!relUserRoleList.isEmpty()){
				relUserRoleInfoService.insertBatchUserRole(relUserRoleList);
			}
			msg = "更新用户角色信息成功";
			
			String result = "对ID为" + userId + "的用户添加角色，角色ID如下:" + roleIds;
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.SUCCESS,result.substring(0, result.length()-1)+"。");
			
			return jsonSuccessResult(msg);
		} catch (ServiceException e) {
			msg = "更新用户角色信息失败";
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			return jsonFailResult(msg);
		} catch (NiceException e) {
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, e.getMessage());
			return jsonFailResult(e.getMessage());
		} catch (Exception e) {
			msg = "更新用户角色信息失败";
			logger.error(msg, e);
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			return jsonFailResult(msg);
		}
	}
	
	/**
	 * 删除用户角色信息，更新数据库
	 */
	@RequestMapping(value = "/user_role_role_del")
	@ResponseBody
	public Map<String, Object> userRoleDel(Model model, String roleId, String userName, HttpSession httpSession) {
		String msg = "";
		try {
			RelUserRole vo = new RelUserRole();
			vo.setUserId(userName.trim());
			vo.setRoleId(roleId);
			relUserRoleInfoService.deleteRelSysUserRole(vo);
			msg = "删除用户角色信息成功";
			
			String result = "对ID为" + userName + "的用户删除角色，角色ID如下:" + roleId;
			safeLog("用户角色配置", "用户角色删除", SUCCESSFAIL.SUCCESS,result);
			
			return jsonSuccessResult(msg);
		} catch (ServiceException e) {
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, e.getMessage());
			return jsonFailResult(e.getMessage());
		} catch (Exception e) {
			msg = "删除用户角色信息失败";
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			logger.error(msg, e);
			return jsonFailResult(msg);
		}
	}

	/**
	 * 批量删除用户角色信息，更新数据库
	 */
	@RequestMapping(value = "/user_role_role_del_batch")
	@ResponseBody
	public Map<String, Object> userRoleDelBatch(Model model, String roleIds, String userName, HttpSession httpSession) {
		String msg = "";
		try {
			String[] roleIdArray = roleIds.split(",");
			for (int i = 0; i < roleIdArray.length; i++) {
				RelUserRole vo = new RelUserRole();
				vo.setUserId(userName.trim());
				vo.setRoleId(roleIdArray[i].trim());
				relUserRoleInfoService.deleteRelSysUserRole(vo);
			}
			msg = "批量删除用户角色信息成功";
			
			String result = "对ID为" + userName + "的用户批量删除角色，角色ID如下:" + roleIds;
			safeLog("用户角色配置", "用户角色批量删除", SUCCESSFAIL.SUCCESS,result);
			
			return jsonSuccessResult(msg);
		} catch (ServiceException e) {
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, e.getMessage());
			return jsonFailResult(e.getMessage());
		} catch (Exception e) {
			msg = "批量删除用户角色信息失败";
			logger.error(msg, e);
			safeLog("用户角色配置", "用户角色添加", SUCCESSFAIL.FAIL, msg);
			return jsonFailResult(msg);
		}
	}
	/**
	 * 跳转到修改密码界面
	 */
	@RequestMapping(value = "/pwd_update")
	@WsdNoNeedAuth
	public String pwdUpdate(Model model, HttpSession httpSession) {
		try {
			if(UAMS.isSelfUser()){
				return "pub/sysmgr/usermgr/update_pwd";
			}else{
				return toAlertPage(model, "请在统一用户管理员系统进行密码修改.");
			}
		} catch (Exception e) {
			logger.error("跳转到修改密码界面错误",e);
			return toAlertPage(model, "系统异常");
		}
	}
	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/update_pwd")
	@ResponseBody
	@WsdNoNeedAuth
	public Map<String, Object> updatePwd(Model model, String oldPwd, String newPwd, HttpSession httpSession) {
		try {
			 boolean exist = userMgrService.isPasswdExist(getUid(httpSession), oldPwd);
			 if(exist){
				 safeLog("用户管理", "修改用户密码", SUCCESSFAIL.SUCCESS,"修改用户密码成功");
				 userMgrService.updateUserPasswd(getUid(httpSession),newPwd);
				 return jsonSuccessResult("修改用户密码成功");
			 }else{
				 return jsonFailResult("原始密码错误");
			 }
		}catch (NiceException e) {
			safeLog("用户管理", "修改用户密码", SUCCESSFAIL.FAIL, e.getMessage());
			return jsonFailResult( e.getMessage());
		} catch (ServiceException e) {
			safeLog("用户管理", "修改用户密码", SUCCESSFAIL.FAIL, e.getMessage());
			return jsonFailResult("修改用户密码失败");
		}
	}
	/**
	 * 验证老密码是否存在
	 */
	@RequestMapping(value = "/check_pwd")
	@ResponseBody
	@WsdNoNeedAuth
	public String checkPwd(Model model, String oldPwd, HttpSession httpSession) {
		try {
			 boolean exist = userMgrService.isPasswdExist(getUid(httpSession), oldPwd);
			 if(exist){
				 return FORM_CHECK_SUCCESS;
			 }else{
				 return FORM_CHECK_FAIL;
			 }
		}catch (ServiceException e) {
			return FORM_CHECK_FAIL;
		} 
	}
	public static void main(String[] args) {
		System.out.println(4|8);
	}
}

